package time;

import userInterface.TextOutput;

/** 
 * The Timer Class, used to time the execution of a piece of code. 
 * NOT THREAD SAFE! 
 */
public class Timer {

    private final TextOutput txtOutput;
    
    private long start_time, elapsed_time;

    /**
     * Creates a Timer object that will not display anything to the screen.
     */
    public Timer() {
        this(false);
    }

    /**
     * Creates a Timer object that will display to the screen if print is
     * true, and will not display to the screen if print is false.
     * 
     * @param print 
     */
    public Timer(boolean print) {
        txtOutput = new TextOutput(print);
    }

    /**
     * Creates a Timer object that will display to the screen using the given
     * TextOutput.
     * 
     * @param txtOutput 
     */
    public Timer(TextOutput txtOutput){
        this.txtOutput = txtOutput;
    }

    /** 
     * Start the timer. 
     */
    public void start() {
        start_time = System.currentTimeMillis();
    }

    /** 
     * Start the timer, and displaying the given message. 
     * 
     * @param msg the message to be shown to the screen 
     */
    public void start(String msg) {
        txtOutput.println(msg + " ... Timing Started.");
        start();
    }

    /**
     * Returns the elapsed time in millisecond. Example if this timer
     * started at 10:00:45 am and this method was called at 10:01:15 then
     * this method would return 30, indicating 30 millisecond has passed
     * since this timer started.
     * 
     * @return 
     */
    public long getElapsedTime() {
        elapsed_time = System.currentTimeMillis() - start_time;
        return elapsed_time;
    }

    /** 
     * Stop the timer. 
     * 
     * @return the time elapsed from the last call to start() to the current
     * call to stop()
     */
    public long stop() {
        return getElapsedTime();
    }

    /** 
     * Stop the timer, and display the given message along with the time
     * elapsed in seconds. 
     * 
     * @param message the message to be display to the screen
     * @return the elapsed time since the last call to start() 
     */
    public long stop(String message) {
        stop();
        txtOutput.println(message + " ... Elapsed time: " + 
                (elapsed_time / 1000.0) + " seconds");
        return elapsed_time;
    }
}
